import { fetchAllList } from "~/admin/api/dict";
import { fetchTree } from "~/admin/api/dept";
import { getUnReasMsg } from "~/admin/api/message";
import dbl from "../utils/dbl";
import router from "@/router";

export default {
	//菜单展开、收缩
	toggleMenu (state) {
		state.expandMenu = !state.expandMenu;
	},
	changeMenuType (state, value) {
		state.currentHeaderMenu = state.headerMenu.find(
			menu => menu.value === value
		);
	},
	// 内嵌页面隐藏多余内容
	resetWebViewStyle (state, value) {
		state.isWebView = value;
	},
	//初始化数据
	init (state) {
		let winWidth = document.body.clientWidth;
		state.isMobile = winWidth < 800;
		if (state.isMobile) {
			state.expandMenu = false;
		}

		let routerTabs = dbl.get("router-tabs");
		state.historyRoutes = routerTabs || [];
	},
	getDict (state) {
		let dict = dbl.get("dict");
		if (dict) {
			state.dict = dict;
		}
		fetchAllList().then(resp => {
			let list = resp.data.data;
			state.dict = list || [];
			dbl.set("dict", state.dict);
		});
	},
	getDepts (state) {
		fetchTree().then(resp => {
			state.depts = resp.data.data || [];
		});
	},
	getCity (state) {

	},
	getUnreadMsg (state) {
		getUnReasMsg().then(resp => {
			state.unreadMsg = resp.data.data;
		});
	},

	addHistoryRoute (state, route) {
		if (route.path === "/login") {
			return;
		}
		let r = state.historyRoutes.find(data => data.path === route.fullPath);
		if (!r && !["/dashboard", "/error403"].includes(route.fullPath)) {
			state.historyRoutes.push({
				label: route.meta.title || "页面标题",
				path: route.fullPath
			});
			dbl.set("router-tabs", state.historyRoutes);
		}
	},
	delHistoryRoute (state, path) {
		let index = state.historyRoutes.findIndex(data => data.path === path);
		if (index > -1) {
			state.historyRoutes.splice(index, 1);
			dbl.set("router-tabs", state.historyRoutes);
		}
		// 关闭页面时返回上一页或者首页
		let history = state.historyRoutes.filter(item => item.path != "/dashboard");

		if (history.length) {
			//判断是否是当前页面，非当前页面的话跳转到路由栈最后一个
			let skipUrl = history.pop().path;
			window.location.pathname.split("/").pop() != skipUrl &&
				router.replace(skipUrl);
		} else {
			path !== "/dashboard" && router.replace("/");
		}
	},
	delLastRoute (state, path) {
		let index = state.historyRoutes.findIndex(data => data.path.includes(path));
		if (index > -1) {
			state.historyRoutes.splice(index, 1);
			dbl.set("router-tabs", state.historyRoutes);
		}
		router.back();
	},
	// 关闭全部标签页
	cleanHistoryRoute (state, path) {
		if (path) {
			let data = state.historyRoutes.find(data => data.path === path);
			data ? (state.historyRoutes = [data]) : router.push(path || "/");
		} else {
			state.historyRoutes = [];
		}
	},
	changeTitle (state, title) {
		state.title = title;
	},
	changeCurrentMenu (state, currentMenu) {
		// console.log(currentMenu);
		state.currentMenu = currentMenu;
	},
	//消息中心
	changeMessagesTotal (state, value) {
		state.messagesTotal = value;
	},
	//消息中心
	changePropertyViewFlag (state, value) {
		state.propertyViewFlag = value;
	}
};
